<template>
  <el-dialog v-model="dialogVisible" title="选择主客户" width="800px" @closed="handleDialogClosed">
    <div class="customer-selector-container">
      <!-- 客户搜索 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入客户名称搜索"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>

      <!-- 客户列表 -->
      <div class="customer-list">
        <el-table
          :data="filteredCustomers"
          height="400"
          border
          highlight-current-row
          @current-change="handleCustomerSelect"
          empty-text="暂无客户数据"
          v-loading="loading"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="客户名称" width="180" />
          <el-table-column prop="customer_type_text" label="客户类型" width="120" />
          <el-table-column prop="source_text" label="客户来源" width="120" />
          <el-table-column prop="address" label="地址" />
          <el-table-column prop="contact_name" label="联系人" width="100" />
          <el-table-column prop="contact_mobile" label="联系电话" width="120" />
        </el-table>
      </div>
    </div>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="confirmSelection" :disabled="!selectedCustomer">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import { customerApi } from '@/api/customer'
  import type { ApiResponse } from '@/types/api'
  import type { Customer } from '@/types/customer'

  interface Props {
    modelValue: boolean
    currentCustomerId?: string | number // 当前客户ID，用于排除
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'select', customer: Customer): void
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    currentCustomerId: '',
  })

  const emit = defineEmits<Emits>()

  // 对话框可见性
  const dialogVisible = ref(props.modelValue)

  // 客户列表
  const customerList = ref<Customer[]>([])

  // 选中的客户
  const selectedCustomer = ref<Customer | null>(null)

  // 搜索关键词
  const searchKeyword = ref('')

  // 加载状态
  const loading = ref(false)

  // 监听外部modelValue变化
  const dialogVisibleWatcher = computed({
    get: () => props.modelValue,
    set: value => {
      emit('update:modelValue', value)
    },
  })

  // 过滤后的客户列表
  const filteredCustomers = computed(() => {
    if (!searchKeyword.value) {
      return customerList.value
    }
    return customerList.value.filter(customer => customer.name?.includes(searchKeyword.value!))
  })

  /**
   * 加载客户列表数据
   */
  const loadCustomers = async () => {
    loading.value = true
    try {
      const response = await customerApi.getMainCustomerList({ page: 1, limit: 1000 })
      if (response.code === 0 && response.data && Array.isArray(response.data.list)) {
        // 过滤掉当前客户
        const filteredList = response.data.list.filter(
          (item: Customer) => String(item.id) !== String(props.currentCustomerId)
        )
        customerList.value = filteredList
      } else {
        ElMessage.error('获取客户列表失败')
      }
    } catch (error) {
      console.error('获取客户列表出错:', error)
      ElMessage.error('获取客户列表失败')
    } finally {
      loading.value = false
    }
  }

  /**
   * 处理搜索操作
   */
  const handleSearch = () => {
    // 搜索逻辑已通过computed实现
  }

  /**
   * 处理客户选择
   * @param customer 选中的客户对象
   */
  const handleCustomerSelect = (customer: Customer) => {
    selectedCustomer.value = customer
  }

  /**
   * 确认选择客户
   */
  const confirmSelection = () => {
    if (selectedCustomer.value) {
      emit('select', selectedCustomer.value)
      dialogVisible.value = false
    } else {
      ElMessage.warning('请选择一个主客户')
    }
  }

  /**
   * 对话框关闭时重置选择状态
   */
  const handleDialogClosed = () => {
    selectedCustomer.value = null
    searchKeyword.value = ''
  }

  /**
   * 打开选择器 - 暴露给父组件使用
   */
  const open = () => {
    dialogVisible.value = true
    loadCustomers()
  }

  // 监听props变化
  watch(
    () => props.modelValue,
    newValue => {
      dialogVisible.value = newValue
      if (newValue) {
        loadCustomers()
      }
    }
  )

  // 暴露方法给父组件
  defineExpose({
    open,
  })
</script>

<style scoped>
  .customer-selector-container {
    display: flex;
    flex-direction: column;
  }

  .search-bar {
    margin-bottom: 16px;
  }

  .customer-list {
    flex: 1;
    overflow: auto;
  }
</style>
